package indi.zhifa.recipe.bailan.framework.common.util.xml;

import indi.zhifa.recipe.bailan.framework.common.entity.exception.ServiceException;
import jakarta.xml.bind.JAXBContext;
import jakarta.xml.bind.JAXBException;
import jakarta.xml.bind.Unmarshaller;
import lombok.extern.slf4j.Slf4j;

import java.io.StringReader;

/**
 * XmlBeanUtil Created by IntelliJ IDEA.
 *
 * @Author: 芝法酱
 * @Create 2021/3/16 15:42
 */
@Slf4j
public class XmlBeanUtil {

    public static <T> T xmlToBean(String xml, Class<T> c) {
        T t = null;
        try {
            JAXBContext context = JAXBContext.newInstance(c);
            Unmarshaller unmarshaller = context.createUnmarshaller();
            t = (T) unmarshaller.unmarshal(new StringReader(xml));
        } catch (JAXBException e) {
            log.error("转换xml时发生错误，错误信息是 " + e.toString());
            throw new ServiceException("转换xml时发生错误，错误信息是 " + e.toString());
        } catch (Exception ex) {
            log.error("转换xml时发生未知错误，错误信息是 " + ex.toString());
            throw new ServiceException("转换xml时发生未知错误，错误信息是 " + ex.toString());
        }
        return t;
    }

}
